// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import loginApi from '@/api/login'
import { Message } from 'element-ui'

const state = {
  userid: '',
  token: getToken(),
  name: '',
  nickname: '',
  avatar: '',
  roles: [],
  remark: '',
  email: '',
  phone: ''
}

const mutations = {
  SET_USERID: (state, userid) => {
    state.userid = userid
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_REMARK: (state, remark) => {
    state.remark = remark
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginApi.login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        console.log(data)
        setToken(data)
        resolve()
      }).catch(error => {
        Message.error('用户或密码有误!')
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
      //   const { data } = response
      loginApi.getInfo(state.token).then(response => {
        const { data } = response
        console.log(data)
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        // const { roles, name, avatar } = data
        const { id, roles, nickname, remark, username, headpath, email, phone } = data
        const BASEURL = "https://image.zysuyuan.cn:8031/"

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // commit('SET_ROLES', roles)
        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        console.log('用户权限:' , roles)
        Message.success('欢迎回来，亲爱的' + data.nickname)
        commit('SET_USERID', id)
        commit('SET_ROLES', roles)
        console.log(state.roles)
        commit('SET_NAME', username)
        if (nickname != null) {
          commit('SET_NICKNAME', nickname)
        } else {
          commit('SET_NICKNAME', '')
        }
        if (remark != null) {
          commit('SET_REMARK', remark)
        } else {
          commit('SET_REMARK', '')
        }
        commit('SET_AVATAR', BASEURL + headpath)
        localStorage.setItem("avatar",BASEURL + headpath)
        if (email != email) {
          commit('SET_EMAIL', email)
        } else {
          commit('SET_EMAIL', '')
        }
        if (phone != null) {
          commit('SET_PHONE', phone)
        } else {
          commit('SET_PHONE', '')
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      loginApi.logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // 清空之前访问的路由，需要先声明dispatch
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 前端 登出
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

